<?php
declare (strict_types = 1);

namespace app\product\service;

use app\product\model\CategoryModel;

class CategoryService extends BaseService
{
    public function __construct(CategoryModel $categoryModel)
    {
        $this->categoryModel = $categoryModel;
    }

    public function model(){
        return $this->categoryModel;
    }

    public function list(array $where = [] , array $limit = [], array $sort= []){
        $limit = check_limit($limit);
        $sort = check_sort($sort);
        return $this->categoryModel->where($where)->limit($limit['page'],$limit['pagesize'])->order($sort[0],$sort[1])->select();
    }

    public function select(array $where = [],array $field = ['*'],array $whereIn = []){
        $model = $this->categoryModel;
        $model = $model->field($field)->where($where);
        if(!empty($whereIn)) $model = $model->whereIn($whereIn[0],$whereIn[1]);
        return $model->select();
    }

    public function count(array $where = [],array $whereIn = []){
        $model = $this->categoryModel;
        $model = $model->where($where);
        if(!empty($whereIn)) $model = $model->whereIn($whereIn[0],$whereIn[1]);
        return $model->count();
    }

    public function find(array $where = []){
        return $this->categoryModel->where($where)->find();
    }

    public function value(array $where = [], string $column = ''){
        return $this->categoryModel->where($where)->value($column);
    }

    public function insertGetId(array $data = []){
        return $this->categoryModel->insertGetId($data);
    }

    public function insertAll(array $data = []){
        return $this->categoryModel->insertAll($data);
    }

    public function update(array $where = [],array $data = []){
        return $this->categoryModel->where($where)->update($data);
    }

    public function delete(array $whereIn = []){
        return $this->categoryModel->whereIn($whereIn[0],$whereIn[1])->delete();
    }

    public function tree(array $forums = [], int $fup=0){
        $result = array();
        $num = -1;
        for($i=0;$i<count($forums);$i++) {
            $form = $forums[$i];
            if($form['pid']==$fup) {
                ++$num;
                $result[$num]['value'] = $form['id'];
                $result[$num]['label'] = $form['name'];
                // 递归循环
                $return_go = $this->tree($forums,$form['id']);
                $result[$num]['children'] = $return_go;
            }
        }
        return $result;
    }
}
